package com.indicator.spring.service;

import com.indicator.spring.model.Coffee;
import com.indicator.spring.model.CoffeeOrder;
import com.indicator.spring.model.OrderState;
import com.indicator.spring.repository.CoffeeOrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @author 超
 * Create by fengc on  2022/9/22 19:48
 */
@Slf4j
@Service
public class CoffeeOrderService {

    @Resource
    private CoffeeOrderRepository orderRepository;

    public CoffeeOrder get(Long id) {
        return orderRepository.getById(id);
    }

    public CoffeeOrder createOrder(String customer, Coffee ...coffees) {
        CoffeeOrder order =
                orderRepository.save(
                        CoffeeOrder.builder().customer(customer).items(Arrays.asList(coffees)).state(OrderState.INIT).build());
        log.info("save order: {}", order);
        return order;
    }

    public boolean updateState(CoffeeOrder order, OrderState state) {
        if (state.compareTo(order.getState()) <= 0) {
            log.warn("Wrong State order: {}, {}", state, order.getState());
            return false;
        }
        order.setState(state);
        orderRepository.save(order);
        log.info("Updated Order: {}", order);
        return true;
    }
}
